package me.dm7.barcodescanner.zbar;

import android.graphics.Bitmap;

import java.util.HashMap;
import java.util.Map;

import me.zxingcore.BarcodeFormat;
import me.zxingcore.EncodeHintType;
import me.zxingcore.MultiFormatWriter;
import me.zxingcore.WriterException;
import me.zxingcore.common.BitMatrix;
import me.zxingcore.qrcode.decoder.ErrorCorrectionLevel;

public class ZBarcodeEncoder {

    private int mForeground = 0xFF000000;
    private int mBackground = 0xFFFFFFFF;

    private Map<EncodeHintType, Object> mDefaultHints;
    private int mDefaultMargin = 1;


    public ZBarcodeEncoder() {
        mDefaultHints = new HashMap<>();
        mDefaultHints.put(EncodeHintType.MARGIN, mDefaultMargin);
        mDefaultHints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        mDefaultHints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    }

    public Bitmap createBitmap(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = matrix.get(x, y) ? mForeground : mBackground;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException {
        return new MultiFormatWriter().encode(contents, format, width, height, mDefaultHints);
    }

    public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {
        return new MultiFormatWriter().encode(contents, format, width, height, hints);
    }

    public Bitmap encodeBitmap(String contents, BarcodeFormat format, int width, int height) throws WriterException {
        return createBitmap(encode(contents, format, width, height));
    }

    public Bitmap encodeBitmap(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {
        return createBitmap(encode(contents, format, width, height, hints));
    }

    public void setMargin(int margin) {
        mDefaultMargin = margin;
        mDefaultHints.put(EncodeHintType.MARGIN, mDefaultMargin);
    }

    public void setForeground(int foregroundColor) {
        this.mForeground = foregroundColor;
    }

    public void setBackground(int backgroundColor) {
        this.mBackground = backgroundColor;
    }

    public void setHints(Map<EncodeHintType, Object> hints) {
        this.mDefaultHints = hints;
    }

    public Map<EncodeHintType, Object> getDefaultHints() {
        return mDefaultHints;
    }
}
